import { loginByPassword, getcode, loginByCode } from '@/api'
import { setToken } from '@/utils/auth'
import router from '@/router'

const state = {
    vcode: ''
}

const mutations = {
    SET_VCODE: (state, vcode) => {
        state.vcode = vcode
    }
}

const actions = {
    login ({ commit }, params) {
        return new Promise(resolve => {
            const { userCode, password, type } = params
            const opt = type ? loginByPassword : loginByCode
            const param = type ? { userCode, password } : { mobile: userCode, vcode: password }
            opt(param).then(res => {
                if (res.code === 200) {
                    setToken(res.data.token)
                    router.replace('/')
                }
                resolve(res)
            })
        })
    },
    getCode ({ commit }, mobile) {
        return new Promise(resolve => {
            getcode({ mobile }).then(res => {
                if (res.code === 200) {
                    commit('SET_VCODE', res.data)
                }
                resolve(res)
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}